#!/usr/bin/env bash
set -e
set -u
set -o pipefail
# -*- Mode: shell -*-

get-date() {
    # sed -n '/#+DATE/p' ${file} | sed -n -e 's/<//p' | sed -n -e 's/>//p' | awk -F ': ' '{ printf $2 }'
    echo `sed -n -e 's/#+DATE://p' $1 \
         | sed -n -e 's/<//p' | sed -n -e 's/>//p'`
}
get-desc() {
    echo `sed -n -e 's/#+DESCRIPTION://p' $1`
}
get-keyw() {
    echo `sed -n -e 's/#+KEYWORDS://p' $1`
}
get-link() {
    echo '.'${1:4}
}
get-titl() {
    echo `sed -n -e 's/#+TITLE://p' $1`
}
get-entry() {
    local file=$1
    #NOTE: I don't think I want the keywords right now.
    # `get-keyw $file`'\n'\
    echo -e '* '`get-date $file` - `get-titl $file`'\n'\
'[[file:'`get-link $file`']['`get-desc $file`'...]]\n'
}
error-exit() {
    echo "Missing: "$1
    exit 1
}

build-home-page_main() {
    local homePage1=template/home-page-1.org
    local headlines=headlines.org
    local homePage2=template/home-page-2.org
    local outfile=site/index.org

    if [ -f "$homePage1" ]; then
        echo "$(cat $homePage1)" > $outfile
        echo '' >> $outfile
    else
	error-exit $homePage1
    fi

    if [ -f "$headlines" ]; then
        echo "$(cat $headlines)" >> $outfile
        echo '' >> $outfile
    else
	error-exit $headlines
    fi

    local array=(\
          ` grep -irn '#+Date' site/archive/ \
          | awk -F ':' '{print $4":"$5"|"$1}' \
          | sort -r \
          | head -n 5 \
          | awk -F '|' '{print $2}'`)
    for file in "${array[@]}"
    do
        echo -e "`get-entry $file`" >> $outfile
	echo '' >> $outfile
    done

    if [ -f "$homePage2" ]; then
        echo "$(cat $homePage2)" >> $outfile
    else
	error-exit $homePage2
    fi
}

build-home-page_main $@
